using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Runtime.InteropServices;
using System.Windows;
using DesktopHelper.Services;
using DesktopHelper.Data;
using DesktopHelper.ViewModels;
using DesktopHelper.Views;

namespace DesktopHelper
{
    public partial class App : Application
    {
        [DllImport("kernel32.dll")]
        static extern bool AllocConsole();
        
        [DllImport("kernel32.dll")]
        static extern bool AttachConsole(int dwProcessId);
        
        public IHost? Host { get; private set; }

        protected override void OnStartup(StartupEventArgs e)
        {
            try
            {
                // 分配控制台窗口用于显示日志
                AllocConsole();
                Console.Title = "桌面助手 - 启动日志";
                Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] 桌面助手启动开始...");
                
                var builder = Microsoft.Extensions.Hosting.Host.CreateApplicationBuilder();
                
                // 配置日志记录
                builder.Services.AddLogging(configure =>
                {
                    configure.AddConsole();
                    configure.SetMinimumLevel(LogLevel.Information);
                });
                
                // 注册服务
                Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] 注册依赖注入服务...");
                builder.Services.AddSingleton<DatabaseService>();
                builder.Services.AddSingleton<ClipboardService>();
                builder.Services.AddSingleton<ScreenshotService>();
                builder.Services.AddSingleton<HotkeyService>();
                builder.Services.AddSingleton<TrayService>();
                builder.Services.AddSingleton<PinnedImageService>();
                
                // 注册ViewModels
                builder.Services.AddTransient<MainViewModel>();
                builder.Services.AddTransient<ViewModels.SettingsViewModel>();
                
                // 注册Views
                builder.Services.AddTransient<MainWindow>();
                builder.Services.AddTransient<Views.SettingsWindow>();
                
                Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] 构建依赖注入容器...");
                Host = builder.Build();

                var logger = Host.Services.GetRequiredService<ILogger<App>>();
                logger.LogInformation("桌面助手应用正在启动...");

                base.OnStartup(e);

                // 在UI线程完全初始化后再启动服务
                Dispatcher.BeginInvoke(new System.Action(() =>
                {
                    StartServices(logger);
                }), System.Windows.Threading.DispatcherPriority.Loaded);

                // 不显示主窗口，通过托盘访问
                // var mainWindow = Host.Services.GetRequiredService<MainWindow>();
                // mainWindow.Show();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] ❌ 启动异常: {ex.Message}");
                Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] 异常类型: {ex.GetType().Name}");
                Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] 堆栈跟踪: {ex.StackTrace}");
                if (ex.InnerException != null)
                {
                    Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] 内部异常: {ex.InnerException.Message}");
                }
                Console.WriteLine("按任意键退出...");
                Console.ReadKey();
                Environment.Exit(-1);
            }
        }
        
        private void StartServices(ILogger<App> logger)
        {
            try
            {
                logger.LogInformation("初始化数据库...");
                // 初始化数据库
                try
                {
                    var dbService = Host.Services.GetRequiredService<DatabaseService>();
                    dbService.Initialize();
                    logger.LogInformation("数据库初始化完成");
                }
                catch (Exception dbEx)
                {
                    logger.LogError(dbEx, "数据库初始化失败");
                    Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] 数据库初始化失败: {dbEx.Message}");
                    // 暂时跳过数据库初始化，继续启动其他服务
                }

                logger.LogInformation("启动剪贴板监听服务...");
                // 启动核心服务
                try
                {
                    var clipboardService = Host.Services.GetRequiredService<ClipboardService>();
                    clipboardService.StartMonitoring();
                    logger.LogInformation("剪贴板监听服务已启动");
                }
                catch (Exception clipEx)
                {
                    logger.LogError(clipEx, "剪贴板服务启动失败");
                    Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] 剪贴板服务启动失败: {clipEx.Message}");
                }

                logger.LogInformation("注册全局快捷键...");
                try
                {
                    var hotkeyService = Host.Services.GetRequiredService<HotkeyService>();
                    hotkeyService.RegisterHotkeys();
                    logger.LogInformation("全局快捷键注册完成");
                }
                catch (Exception hotkeyEx)
                {
                    logger.LogError(hotkeyEx, "全局快捷键注册失败");
                    Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] 全局快捷键注册失败: {hotkeyEx.Message}");
                }

                logger.LogInformation("初始化系统托盘...");
                try
                {
                    var trayService = Host.Services.GetRequiredService<TrayService>();
                    trayService.Initialize();
                    logger.LogInformation("系统托盘初始化完成");
                }
                catch (Exception trayEx)
                {
                    logger.LogError(trayEx, "系统托盘初始化失败");
                    Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] 系统托盘初始化失败: {trayEx.Message}");
                }

                logger.LogInformation("✅ 桌面助手应用启动完成！应用已最小化到系统托盘");
                Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] ✅ 启动成功！应用运行在系统托盘中");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "服务启动失败");
                Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] ❌ 服务启动失败: {ex.Message}");
            }
        }

        protected override void OnExit(ExitEventArgs e)
        {
            Host?.Dispose();
            base.OnExit(e);
        }
    }
}